package com.whzjkj.gateway.server.processor;

import com.whzjkj.gateway.server.codce.JT808MessageEncoder;
import com.whzjkj.gateway.server.session.Session;
import com.whzjkj.gateway.server.session.TCPSessionManager;
import com.whzjkj.gateway.vo.PackageData;
import com.whzjkj.gateway.vo.ServerCommonRespondBody;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @description: 消息处理
 * @author: Mr.Hu
 * @create: 2018-11-01 09:42
 **/
@Slf4j
public abstract class AbstractMessageProcessor implements TerminalMessageProcessor{

    @Resource
    private TCPSessionManager sessionManager;
    /**
     * 发送消息
     * @param channel
     * @param msg
     * @throws InterruptedException
     */
    protected void sendMessage(Channel channel, byte[] msg) throws InterruptedException {
        ChannelFuture future = channel.writeAndFlush(Unpooled.copiedBuffer(msg)).sync();
        if (!future.isSuccess()) {
            log.error("发送数据出错:{}", future.cause());
        }
    }

    protected int getFlowNo(Channel channel, int defaultValue) {
        Session session = sessionManager.findBySessionId(Session.buildId(channel));
        if (session == null) {
            return defaultValue;
        }
        return session.currentFlowNo();
    }

    protected int getFlowNo(Channel channel) {
        return this.getFlowNo(channel, 0);
    }

    /**
     * 平台通用应答
     * @param req
     * @throws InterruptedException
     */
    protected void serverCommonRespond(PackageData req) throws InterruptedException, IOException {
        ServerCommonRespondBody respondBody = new ServerCommonRespondBody();
        respondBody.setRespondFlowNo(req.getMessageHeader().getMessageFlowNo())
            .setRespondMessageId(req.getMessageHeader().getMessageId())
            .setRespondCode(ServerCommonRespondBody.ServerCommonRespondBodyEnum.RESPONDCODE_SUCCESS.code);
        int flowNo = getFlowNo(req.getChannel());
        byte[] msg = JT808MessageEncoder.encoderServerCommonRespondMessage(req, respondBody, flowNo);
        sendMessage(req.getChannel(), msg);
    }
}
